package sort;

import java.util.Arrays;
import java.util.Random;

import static util.SwapUtil.swap;

/**
 * @BelongsProject: leetcode
 * @BelongsPackage: sort
 * @author: 肖
 * @date: 2022/1/24 10:59
 * @Description: 快排
 * @since JDK 11
 */

public class QuickSort {
    public static void quickSort(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
        quickSort(arr, 0, arr.length - 1);
    }


    public static void quickSort(int[] arr, int l, int r) {
        if (l < r) {
//            等概率交换
            swap(arr, l + (int) (Math.random() * (r - l + 1)), r);
            int[] p = partition(arr, l, r);
//            小于区间
            quickSort(arr, l, p[0] - 1);
//            大于区间
            quickSort(arr, p[1] + 1, r);
        }
    }


    public static int[] partition(int[] arr, int l, int r) {
        int less = l - 1;
        int more = r;
        while (l < more) {
            if (arr[l] < arr[r]) {
                swap(arr, ++less, l++);
            } else if (arr[l] > arr[r]) {
                swap(arr, --more, l);
            } else {
                l++;
            }
        }
        swap(arr, more, r);
        return new int[]{less + 1, more};
    }


    public static void main(String[] args) {

        int arr[] = {2, 3, 4, 5, 6, 1};
        swap(arr, 2, 3);
        for (int i : arr) {
            System.out.println(i);
        }
    }

}
